


package ciicos.equ.controller;

import ciicos.annotation.JnpfField;
import ciicos.base.ActionResult;
import ciicos.base.UserInfo;
import ciicos.base.vo.DownloadVO;
import ciicos.base.vo.PageListVO;
import ciicos.base.vo.PaginationVO;
import ciicos.config.ConfigValueUtil;
import ciicos.equ.entity.EquBaseEntity;
import ciicos.equ.entity.EquPointEntity;
import ciicos.equ.model.equbase.*;
import ciicos.equ.service.EquBaseService;
import ciicos.equ.service.EquPointService;
import ciicos.exception.DataException;
import ciicos.onlinedev.model.OnlineImport.ExcelImFieldModel;
import ciicos.onlinedev.model.OnlineImport.ExcelImportModel;
import ciicos.onlinedev.model.OnlineImport.VisualImportModel;
import ciicos.permission.entity.UserEntity;
import ciicos.util.*;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.xuyanwu.spring.file.storage.FileInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 设备信息
 *
 * @版本： V3.2.0
 * @版权：
 * @作者： 企业研发中心
 * @日期： 2024-02-06
 */
@Slf4j
@RestController
@Api(tags = "设备信息", value = "equManage")
@RequestMapping("/api/equManage/EquBase")
public class EquBaseController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private ConfigValueUtil configValueUtil;

    @Autowired
    private UserProvider userProvider;


    @Autowired
    private EquBaseService equBaseService;

    @Autowired
    private EquPointService equPointService;


    /**
     * 列表
     *
     * @param equBasePagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody EquBasePagination equBasePagination) throws IOException {
        //树形判断是否有参数，有参数不造树
        List<EquBaseEntity> list = equBaseService.getList(equBasePagination);
        //处理id字段转名称，若无需转或者为空可删除

        List<EquBaseListVO> listVO = JsonUtil.getJsonToList(list, EquBaseListVO.class);
        for (EquBaseListVO equBaseVO : listVO) {
            equBaseVO.setPacket_name(generaterSwapUtil.getDicName(equBaseVO.getPacket(), "524477639071639685"));

            equBaseVO.setType_name(generaterSwapUtil.getDicName(equBaseVO.getType(), "524489413061781637"));

            equBaseVO.setName_name(equBaseVO.getName());

            equBaseVO.setCode_name(equBaseVO.getCode());

            equBaseVO.setCreatoruserid_name(generaterSwapUtil.userSelectValue(equBaseVO.getCreatoruserid()));

            equBaseVO.setCreatortime_name(equBaseVO.getCreatortime());

            equBaseVO.setLastmodifyuserid_name(generaterSwapUtil.userSelectValue(equBaseVO.getLastmodifyuserid()));

            equBaseVO.setLastmodifytime_name(equBaseVO.getLastmodifytime());

            equBaseVO.setBrand_name(equBaseVO.getBrand());

            equBaseVO.setModel_name(equBaseVO.getModel());

            equBaseVO.setFactorycode_name(equBaseVO.getFactorycode());

            equBaseVO.setFactorytime_name(equBaseVO.getFactorytime() != null ? new Date(equBaseVO.getFactorytime()) : null);

            equBaseVO.setBuyime_name(equBaseVO.getBuyime() != null ? new Date(equBaseVO.getBuyime()) : null);

            equBaseVO.setLocation_name(equBaseVO.getLocation());

            equBaseVO.setRuningtime_name(equBaseVO.getRuningtime());
        }

        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(equBasePagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param equBaseForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid EquBaseForm equBaseForm) throws DataException {
        String b = equBaseService.checkForm(equBaseForm, 0);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }

        String mainId = RandomUtil.uuId();

        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        equBaseForm.setCreatoruserid(userInfo.getUserId());
        equBaseForm.setCreatortime(DateUtil.getNow());
        EquBaseEntity entity = JsonUtil.getJsonToBean(equBaseForm, EquBaseEntity.class);
        entity.setId(mainId);
        equBaseService.save(entity);
        if (equBaseForm.getEqupointList() != null) {
            List<EquPointEntity> EquPointList = JsonUtil.getJsonToList(equBaseForm.getEqupointList(), EquPointEntity.class);
            for (EquPointEntity entitys : EquPointList) {
                entitys.setId(RandomUtil.uuId());
                entitys.setEquid(entity.getId());

                equPointService.save(entitys);
            }
        }


        return ActionResult.success("创建成功");
    }

    /**
     * 导出Excel
     *
     * @return
     */
    @ApiOperation("导出Excel")
    @PostMapping("/Actions/Export")
    public ActionResult Export(@RequestBody EquBasePagination equBasePagination) throws IOException {
        if (StringUtil.isEmpty(equBasePagination.getSelectKey())) {
            return ActionResult.fail("请选择导出字段");
        }
        List<EquBaseEntity> list = equBaseService.getTypeList(equBasePagination, equBasePagination.getDataType());
        //处理id字段转名称，若无需转或者为空可删除

        List<EquBaseListVO> listVO = JsonUtil.getJsonToList(list, EquBaseListVO.class);
        for (EquBaseListVO equBaseVO : listVO) {
            ActionResult info = info(equBaseVO.getId());
            Map<String, Object> dataMap = JsonUtil.entityToMap(info.getData());
            equBaseVO.setPacket_name(generaterSwapUtil.getDicName(equBaseVO.getPacket(), "524477639071639685"));

            equBaseVO.setType_name(generaterSwapUtil.getDicName(equBaseVO.getType(), "524489413061781637"));

            equBaseVO.setName_name(equBaseVO.getName());

            equBaseVO.setCode_name(equBaseVO.getCode());

            equBaseVO.setCreatoruserid_name(generaterSwapUtil.userSelectValue(equBaseVO.getCreatoruserid()));

            equBaseVO.setCreatortime_name(equBaseVO.getCreatortime());

            equBaseVO.setLastmodifyuserid_name(generaterSwapUtil.userSelectValue(equBaseVO.getLastmodifyuserid()));

            equBaseVO.setLastmodifytime_name(equBaseVO.getLastmodifytime());

            equBaseVO.setBrand_name(equBaseVO.getBrand());

            equBaseVO.setModel_name(equBaseVO.getModel());

            equBaseVO.setFactorycode_name(equBaseVO.getFactorycode());

            equBaseVO.setFactorytime_name(equBaseVO.getFactorytime() != null ?
                    new Date(equBaseVO.getFactorytime()) : null);

            equBaseVO.setBuyime_name(equBaseVO.getBuyime() != null ?
                    new Date(equBaseVO.getBuyime()) : null);

            equBaseVO.setLocation_name(equBaseVO.getLocation());

            equBaseVO.setRuningtime_name(equBaseVO.getRuningtime());

            equBaseVO.setRuningstatus_name(generaterSwapUtil.getDicName(equBaseVO.getRuningstatus(), "524489520037505157"));

            equBaseVO.setDescription_name(equBaseVO.getDescription());

            equBaseVO.setFiles_name(generaterSwapUtil.getFileNameInJson(equBaseVO.getFiles()));

            //子表数据转换
            List<EquPointEntity> equPointList = equBaseService.getEquPointList(equBaseVO.getId(), equBasePagination);
            List<EquPointModel> equPointModelList = JsonUtil.getJsonToList(equPointList, EquPointModel.class);
            int equPointNum = 0;
            for (EquPointModel equPointModel : equPointModelList) {
                equPointModel.setType(generaterSwapUtil.getDicName(equPointModel.getType(), "436925156615521477"));
                equPointNum++;
            }
            equBaseVO.setEquPointList(equPointModelList);
        }

        //转换为map输出
        List<Map<String, Object>> mapList = JsonUtil.getJsonToListMap(JsonUtil.getObjectToStringDateFormat(listVO, "yyyy-MM-dd HH:mm:ss"));
        mapList.stream().forEach(map -> {
            Map<String, Object> map2 = new HashMap<>();
            map.putAll(map2);
            List<Map<String, Object>> tableField120Map = JsonUtil.getJsonToListMap(String.valueOf(map.get("tableField120")));
            for (Map<String, Object> mp : tableField120Map) {
            }
            map.put("tableField120", tableField120Map);
        });
        String[] keys = !StringUtil.isEmpty(equBasePagination.getSelectKey()) ? equBasePagination.getSelectKey().split(",") : new String[0];
        UserInfo userInfo = userProvider.get();
        DownloadVO vo = this.creatModelExcel(configValueUtil.getTemporaryFilePath(), mapList, keys, userInfo);
        return ActionResult.success(vo);
    }

    //导出表格
    public DownloadVO creatModelExcel(String path, List<Map<String, Object>> list, String[] keys, UserInfo userInfo) {
        DownloadVO vo = DownloadVO.builder().build();
        List<ExcelExportEntity> entitys = new ArrayList<>();
        if (keys.length > 0) {
            ExcelExportEntity tableField120ExcelEntity = new ExcelExportEntity("", "tableField120");
            List<ExcelExportEntity> tableField120List = new ArrayList<>();
            for (String key : keys) {
                switch (key) {
                    case "packet":
                        entitys.add(new ExcelExportEntity("设备组", "packet_name"));
                        break;
                    case "type":
                        entitys.add(new ExcelExportEntity("类型", "type_name"));
                        break;
                    case "name":
                        entitys.add(new ExcelExportEntity("名称", "name_name"));
                        break;
                    case "code":
                        entitys.add(new ExcelExportEntity("编号", "code_name"));
                        break;
                    case "creatoruserid":
                        entitys.add(new ExcelExportEntity("创建用户", "creatoruserid_name"));
                        break;
                    case "creatortime":
                        entitys.add(new ExcelExportEntity("创建时间", "creatortime_name"));
                        break;
                    case "lastmodifyuserid":
                        entitys.add(new ExcelExportEntity("修改用户", "lastmodifyuserid_name"));
                        break;
                    case "lastmodifytime":
                        entitys.add(new ExcelExportEntity("修改时间", "lastmodifytime_name"));
                        break;
                    case "brand":
                        entitys.add(new ExcelExportEntity("品牌", "brand_name"));
                        break;
                    case "model":
                        entitys.add(new ExcelExportEntity("型号", "model_name"));
                        break;
                    case "factorycode":
                        entitys.add(new ExcelExportEntity("出厂编码", "factorycode_name"));
                        break;
                    case "factorytime":
                        entitys.add(new ExcelExportEntity("出厂日期", "factorytime_name"));
                        break;
                    case "buyime":
                        entitys.add(new ExcelExportEntity("购买日期", "buyime_name"));
                        break;
                    case "location":
                        entitys.add(new ExcelExportEntity("位置", "location_name"));
                        break;
                    case "runingtime":
                        entitys.add(new ExcelExportEntity("运行时长", "runingtime_name"));
                        break;
                    case "runingstatus":
                        entitys.add(new ExcelExportEntity("运行状态", "runingstatus_name"));
                        break;
                    case "runingtimepoint":
                        entitys.add(new ExcelExportEntity("运行时长点位", "runingtimepoint_name"));
                        break;
                    case "runingstatuspoint":
                        entitys.add(new ExcelExportEntity("运行状态点位", "runingstatuspoint_name"));
                        break;
                    case "description":
                        entitys.add(new ExcelExportEntity("备注", "description_name"));
                        break;
                    case "files":
                        entitys.add(new ExcelExportEntity("附件", "files_name"));
                        break;
                    case "tableField120-code":
                        tableField120List.add(new ExcelExportEntity("点位名称", "code"));
                        break;
                    case "tableField120-name":
                        tableField120List.add(new ExcelExportEntity("点位描述", "name"));
                        break;
                    case "tableField120-type":
                        tableField120List.add(new ExcelExportEntity("点位类型", "type"));
                        break;
                    case "tableField120-jnpf_equ_point_jnpf_node":
                        tableField120List.add(new ExcelExportEntity("点位节点", "jnpf_equ_point_jnpf_node"));
                        break;
                    default:
                        break;

                }
            }
            List<String> keylist = new ArrayList<>();
            for (String key : keys) {
                keylist.add(key);
            }
            if (tableField120List.size() > 0) {
                String tableField120 = keylist.stream().filter(k -> k.startsWith("tableField120")).findFirst().orElse("");
                List<String> tableField120st = keylist.stream().filter(k -> k.startsWith("tableField120")).collect(Collectors.toList());
                tableField120ExcelEntity.setList(tableField120List);
                entitys.add(keylist.indexOf(tableField120), tableField120ExcelEntity);
                keylist.removeAll(tableField120st);
            }
        }

        ExportParams exportParams = new ExportParams(null, "表单信息");
        exportParams.setType(ExcelType.XSSF);
        try {
            @Cleanup Workbook workbook = new HSSFWorkbook();
            if (entitys.size() > 0) {
                if (list.size() == 0) {
                    list.add(new HashMap<>());
                }
                workbook = ExcelExportUtil.exportExcel(exportParams, entitys, list);
            }
            String fileName = "表单信息" + DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + ".xlsx";
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return vo;
    }


    @ApiOperation("上传文件")
    @PostMapping("/Uploader")
    public ActionResult<Object> Uploader() {
        List<MultipartFile> list = UpUtil.getFileAll();
        MultipartFile file = list.get(0);
        if (file.getOriginalFilename().endsWith(".xlsx") || file.getOriginalFilename().endsWith(".xls")) {
            String filePath = XSSEscape.escape(configValueUtil.getTemporaryFilePath());
            String fileName = XSSEscape.escape(RandomUtil.uuId() + "." + UpUtil.getFileType(file));
            //上传文件
            FileInfo fileInfo = FileUploadUtils.uploadFile(file, filePath, fileName);
            DownloadVO vo = DownloadVO.builder().build();
            vo.setName(fileInfo.getFilename());
            return ActionResult.success(vo);
        } else {
            return ActionResult.fail("选择文件不符合导入");
        }
    }

    /**
     * 模板下载
     *
     * @return
     */
    @ApiOperation("模板下载")
    @GetMapping("/TemplateDownload")
    public ActionResult<DownloadVO> TemplateDownload() {
        DownloadVO vo = DownloadVO.builder().build();
        UserInfo userInfo = userProvider.get();
        Map<String, Object> dataMap = new HashMap<>();

        List<ExcelExportEntity> entitys = new ArrayList<>();

        entitys.add(new ExcelExportEntity("类型", "type"));
        entitys.add(new ExcelExportEntity("名称", "name"));
        entitys.add(new ExcelExportEntity("编号", "code"));
        entitys.add(new ExcelExportEntity("创建用户", "creatoruserid"));
        dataMap.put("creatoruserid", "系统自动生成");
        entitys.add(new ExcelExportEntity("创建时间", "creatortime"));
        dataMap.put("creatortime", "系统自动生成");
        entitys.add(new ExcelExportEntity("修改用户", "lastmodifyuserid"));
        dataMap.put("lastmodifyuserid", "系统自动生成");
        entitys.add(new ExcelExportEntity("修改时间", "lastmodifytime"));
        dataMap.put("lastmodifytime", "系统自动生成");
        entitys.add(new ExcelExportEntity("品牌", "brand"));
        entitys.add(new ExcelExportEntity("型号", "model"));
        entitys.add(new ExcelExportEntity("出厂编码", "factorycode"));
        entitys.add(new ExcelExportEntity("出厂日期", "factorytime"));
        dataMap.put("factorytime", "例:yyyy-MM-dd");
        entitys.add(new ExcelExportEntity("购买日期", "buyime"));
        dataMap.put("buyime", "例:yyyy-MM-dd");
        entitys.add(new ExcelExportEntity("位置", "location"));
        entitys.add(new ExcelExportEntity("运行时长", "runingtime"));
        entitys.add(new ExcelExportEntity("运行状态", "runingstatus"));
        entitys.add(new ExcelExportEntity("运行时长点位", "runingtimepoint"));
        entitys.add(new ExcelExportEntity("运行状态点位", "runingstatuspoint"));
        entitys.add(new ExcelExportEntity("备注", "description"));
        entitys.add(new ExcelExportEntity("设备组", "packet"));
        List<Map<String, Object>> list = new ArrayList<>();
        list.add(dataMap);

        ExportParams exportParams = new ExportParams(null, "设备信息模板");
        exportParams.setType(ExcelType.XSSF);
        try {
            @Cleanup Workbook workbook = new HSSFWorkbook();
            if (entitys.size() > 0) {
                if (list.size() == 0) {
                    list.add(new HashMap<>());
                }
                workbook = ExcelExportUtil.exportExcel(exportParams, entitys, list);
            }
            String fileName = "设备信息模板" + DateUtil.dateNow("yyyyMMddHHmmss") + ".xlsx";
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("模板信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return ActionResult.success(vo);
    }

    /**
     * 导入预览
     *
     * @return
     */
    @ApiOperation("导入预览")
    @GetMapping("/ImportPreview")
    public ActionResult<Map<String, Object>> ImportPreview(String fileName) throws Exception {
        Map<String, Object> headAndDataMap = new HashMap<>(2);
        String filePath = FileUploadUtils.getLocalBasePath() + configValueUtil.getTemporaryFilePath();
        FileUploadUtils.downLocal(configValueUtil.getTemporaryFilePath(), filePath, fileName);
        File temporary = new File(XSSEscape.escapePath(filePath + fileName));
        int headerRowIndex = 1;
        ImportParams params = new ImportParams();
        params.setTitleRows(0);
        params.setHeadRows(headerRowIndex);
        params.setNeedVerify(true);
        try {
            List<EquBaseExcelVO> excelDataList = ExcelImportUtil.importExcel(temporary, EquBaseExcelVO.class, params);
            // 导入字段
            List<ExcelImFieldModel> columns = new ArrayList<>();
            columns.add(new ExcelImFieldModel("type", "类型"));
            columns.add(new ExcelImFieldModel("name", "名称"));
            columns.add(new ExcelImFieldModel("code", "编号"));
            columns.add(new ExcelImFieldModel("creatoruserid", "创建用户"));
            columns.add(new ExcelImFieldModel("creatortime", "创建时间"));
            columns.add(new ExcelImFieldModel("lastmodifyuserid", "修改用户"));
            columns.add(new ExcelImFieldModel("lastmodifytime", "修改时间"));
            columns.add(new ExcelImFieldModel("brand", "品牌"));
            columns.add(new ExcelImFieldModel("model", "型号"));
            columns.add(new ExcelImFieldModel("factorycode", "出厂编码"));
            columns.add(new ExcelImFieldModel("factorytime", "出厂日期"));
            columns.add(new ExcelImFieldModel("buyime", "购买日期"));
            columns.add(new ExcelImFieldModel("location", "位置"));
            columns.add(new ExcelImFieldModel("runingtime", "运行时长"));
            columns.add(new ExcelImFieldModel("runingstatus", "运行状态"));
            columns.add(new ExcelImFieldModel("runingtimepoint", "运行时长点位"));
            columns.add(new ExcelImFieldModel("runingstatuspoint", "运行状态点位"));
            columns.add(new ExcelImFieldModel("description", "备注"));
            columns.add(new ExcelImFieldModel("packet", "设备组"));
            headAndDataMap.put("dataRow", excelDataList);
            headAndDataMap.put("headerRow", columns);
        } catch (Exception e) {
            e.printStackTrace();
            return ActionResult.fail("表头名称不可更改,表头行不能删除");
        }
        return ActionResult.success(headAndDataMap);
    }

    /**
     * 导入数据
     *
     * @return
     */
    @ApiOperation("导入数据")
    @PostMapping("/ImportData")
    public ActionResult<ExcelImportModel> ImportData(@RequestBody VisualImportModel visualImportModel) throws Exception {
        List<EquBaseExcelVO> equBaseVOList = JsonUtil.getJsonToList(visualImportModel.getList(), EquBaseExcelVO.class);
        ExcelImportModel excelImportModel = new ExcelImportModel();
        List<Map<String, Object>> errorList = new ArrayList<>();
        for (EquBaseExcelVO vo : equBaseVOList) {
            Map<String, Object> map = JsonUtil.entityToMap(vo);
            Map<String, Object> erroMap = JsonUtil.entityToMap(vo);
            StringJoiner error = new StringJoiner(",");
            //缓存
            Map<String, Object> localcheMap = new HashMap<>();
            String mainID = RandomUtil.uuId();
            localcheMap = generaterSwapUtil.putCache(localcheMap);
            String equBaseid = null;

            generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("type").getAnnotation(JnpfField.class), String.valueOf(vo.getType()), map, localcheMap, error);

            equBaseid = generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("name").getAnnotation(JnpfField.class), String.valueOf(vo.getName()), map, "", localcheMap, error);

            equBaseid = generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("code").getAnnotation(JnpfField.class), String.valueOf(vo.getCode()), map, "", localcheMap, error);

            generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("creatoruserid").getAnnotation(JnpfField.class), String.valueOf(vo.getCreatoruserid()), map, "", localcheMap, error);

            generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("creatortime").getAnnotation(JnpfField.class), String.valueOf(vo.getCreatortime()), map, "", localcheMap, error);

            generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("lastmodifyuserid").getAnnotation(JnpfField.class), String.valueOf(vo.getLastmodifyuserid()), map, "", localcheMap, error);

            generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("lastmodifytime").getAnnotation(JnpfField.class), String.valueOf(vo.getLastmodifytime()), map, "", localcheMap, error);

            equBaseid = generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("brand").getAnnotation(JnpfField.class), String.valueOf(vo.getBrand()), map, "", localcheMap, error);

            equBaseid = generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("model").getAnnotation(JnpfField.class), String.valueOf(vo.getModel()), map, "", localcheMap, error);

            equBaseid = generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("factorycode").getAnnotation(JnpfField.class), String.valueOf(vo.getFactorycode()), map, "", localcheMap, error);

            generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("factorytime").getAnnotation(JnpfField.class), String.valueOf(vo.getFactorytime()), map, "", localcheMap, error);

            generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("buyime").getAnnotation(JnpfField.class), String.valueOf(vo.getBuyime()), map, "", localcheMap, error);

            equBaseid = generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("location").getAnnotation(JnpfField.class), String.valueOf(vo.getLocation()), map, "", localcheMap, error);

            generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("runingtime").getAnnotation(JnpfField.class), String.valueOf(vo.getRuningtime()), map, "", localcheMap, error);

            generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("runingstatus").getAnnotation(JnpfField.class), String.valueOf(vo.getRuningstatus()), map, localcheMap, error);

            generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("description").getAnnotation(JnpfField.class), String.valueOf(vo.getDescription()), map, "", localcheMap, error);

            generaterSwapUtil.excelCheckForm(vo.getClass().getDeclaredField("packet").getAnnotation(JnpfField.class), String.valueOf(vo.getPacket()), map, localcheMap, error);

            if (error.length() > 0) {
                erroMap.put("errorsInfo", error.toString());
                errorList.add(erroMap);
            } else {
                if (equBaseid != null) {
                    this.delete(equBaseid);
                }
                EquBaseEntity equBaseEntity = JsonUtil.getJsonToBean(map, EquBaseEntity.class);
                equBaseEntity.setId(mainID);
                equBaseService.save(equBaseEntity);
            }
        }
        excelImportModel.setSnum(equBaseVOList.size() - errorList.size());
        excelImportModel.setFnum(errorList.size());
        excelImportModel.setResultType(errorList.size() > 0 ? 1 : 0);
        excelImportModel.setFailResult(errorList);
        return ActionResult.success(excelImportModel);
    }

    /**
     * 导出异常报告
     *
     * @return
     */
    @ApiOperation("导出异常报告")
    @PostMapping("/ImportExceptionData")
    public ActionResult<DownloadVO> ImportExceptionData(@RequestBody VisualImportModel visualImportModel) {
        DownloadVO vo = DownloadVO.builder().build();
        List<EquBaseExcelErrorVO> equBaseVOList = JsonUtil.getJsonToList(visualImportModel.getList(), EquBaseExcelErrorVO.class);
        UserInfo userInfo = userProvider.get();

        try {
            @Cleanup Workbook workbook = new HSSFWorkbook();
            ExportParams exportParams = new ExportParams(null, "错误报告");
            exportParams.setType(ExcelType.XSSF);
            workbook = ExcelExportUtil.exportExcel(exportParams,
                    EquBaseExcelErrorVO.class, equBaseVOList);

            String fileName = "错误报告" + DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + ".xlsx";
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ActionResult.success(vo);
    }


    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/batchRemove/{ids}")
    @Transactional
    @ApiOperation("批量删除")
    public ActionResult batchRemove(@PathVariable("ids") String ids) {
        String[] idList = ids.split(",");
        int i = 0;
        for (String allId : idList) {
            this.delete(allId);
            i++;
        }
        if (i == 0) {
            return ActionResult.fail("删除失败");
        }
        return ActionResult.success("删除成功");
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<EquBaseInfoVO> info(@PathVariable("id") String id) {
        EquBaseEntity entity = equBaseService.getInfo(id);
        EquBaseInfoVO vo = JsonUtil.getJsonToBean(entity, EquBaseInfoVO.class);
        vo.setCreatoruserid(generaterSwapUtil.userSelectValue(vo.getCreatoruserid()));
        if (vo.getCreatortime() != null) {
            vo.setCreatortime(vo.getCreatortime());
        }
        vo.setLastmodifyuserid(generaterSwapUtil.userSelectValue(vo.getLastmodifyuserid()));
        if (vo.getLastmodifytime() != null) {
            vo.setLastmodifytime(vo.getLastmodifytime());
        }

        //子表
        List<EquPointEntity> EquPointList = equBaseService.getEquPointList(id);
        for (EquPointEntity equpointEntity : EquPointList) {
        }
        vo.setEquPointList(JsonUtil.getJsonToList(EquPointList, EquPointModel.class));
        //副表
        return ActionResult.success(vo);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<EquBaseInfoVO> detailInfo(@PathVariable("id") String id) {
//        ActionResult info = info(id);
//        Map<String, Object> dataMap = JsonUtil.entityToMap(info.getData());
        EquBaseEntity entity = equBaseService.getInfo(id);
        EquBaseInfoVO vo = JsonUtil.getJsonToBean(entity, EquBaseInfoVO.class);

        //子表数据转换
        List<EquPointEntity> equPointList = equBaseService.getEquPointList(id);
        List<EquPointModel> equPointModelList = JsonUtil.getJsonToList(equPointList, EquPointModel.class);
        int equPointNum = 0;
        for (EquPointModel equPointModel : equPointModelList) {
            equPointModel.setType(generaterSwapUtil.getDicName(equPointModel.getType(), "436925156615521477"));
            equPointNum++;
        }
        vo.setEquPointList(equPointModelList);

        //附表数据转换

        //添加到详情表单对象中
        vo.setPacket(generaterSwapUtil.getDicName(vo.getPacket(), "524477639071639685"));

        vo.setType(generaterSwapUtil.getDicName(vo.getType(), "524489413061781637"));

        vo.setName(vo.getName());

        vo.setCode(vo.getCode());

        vo.setCreatoruserid(generaterSwapUtil.userSelectValue(vo.getCreatoruserid()));

        vo.setCreatortime(vo.getCreatortime());

        vo.setLastmodifyuserid(generaterSwapUtil.userSelectValue(vo.getLastmodifyuserid()));

        vo.setLastmodifytime(vo.getLastmodifytime());

        vo.setBrand(vo.getBrand());

        vo.setModel(vo.getModel());

        vo.setFactorycode(vo.getFactorycode());

        vo.setFactorytime(vo.getFactorytime());

        vo.setBuyime(vo.getBuyime());

        vo.setLocation(vo.getLocation());

        vo.setRuningtime(vo.getRuningtime());

        vo.setRuningstatus(generaterSwapUtil.getDicName(vo.getRuningstatus(), "524489520037505157"));

        vo.setDescription(vo.getDescription());

        vo.setFiles(generaterSwapUtil.getFileNameInJson(vo.getFiles()));


        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @param equBaseForm
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid EquBaseForm equBaseForm) throws DataException {
        String b = equBaseService.checkForm(equBaseForm, 1);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }
        UserInfo userInfo = userProvider.get();
        EquBaseEntity entity = equBaseService.getInfo(id);
        if (entity != null) {
            equBaseForm.setLastmodifyuserid(userInfo.getUserId());
            equBaseForm.setLastmodifytime(DateUtil.getNow());
            EquBaseEntity subentity = JsonUtil.getJsonToBean(equBaseForm, EquBaseEntity.class);
            subentity.setCreatoruserid(entity.getCreatoruserid());
            subentity.setCreatortime(entity.getCreatortime());
            //保养周期
            Double upkeepCycle = equBaseForm.getUpkeepCycle();
            //上次保养日期
            String lastUpkeepDate = equBaseForm.getNextUpkeepDate();
//            DateUtil

            boolean b1 = equBaseService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }

            QueryWrapper<EquPointEntity> EquPointqueryWrapper = new QueryWrapper<>();
            EquPointqueryWrapper.lambda().eq(EquPointEntity::getEquid, entity.getId());
            equPointService.remove(EquPointqueryWrapper);
            if (equBaseForm.getEqupointList() != null) {
                List<EquPointEntity> EquPointList = JsonUtil.getJsonToList(equBaseForm.getEqupointList(), EquPointEntity.class);
                for (EquPointEntity entitys : EquPointList) {

                    entitys.setId(RandomUtil.uuId());
                    entitys.setEquid(entity.getId());
                    equPointService.save(entitys);
                }
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        EquBaseEntity entity = equBaseService.getInfo(id);
        if (entity != null) {
            equBaseService.delete(entity);
            QueryWrapper<EquPointEntity> queryWrapperEquPoint = new QueryWrapper<>();
            queryWrapperEquPoint.lambda().eq(EquPointEntity::getEquid, entity.getId());

            equPointService.remove(queryWrapperEquPoint);
        }
        return ActionResult.success("删除成功");
    }

    @ApiOperation("根据编号查询点位")
    @GetMapping("/detail/{id}/{code}")
    public ActionResult<EquPointEntity> detailInfo(@PathVariable("id") String id, @PathVariable("code") String code) {
        List<EquPointEntity> listByNmae = equPointService.getListByCdoe(id, code);
        if (listByNmae.size() > 0) {
            return ActionResult.success(listByNmae.get(0));
        }
        return ActionResult.success();
    }

}
